package murraco.service.impl;

import murraco.constants.PileConstants;
import murraco.dto.PileResponseDto;
import murraco.model.Pile;
import murraco.repository.PileRepository;
import murraco.service.PileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class PileServiceImpl implements PileService {

    private final PileRepository pileRepository;

    @Autowired
    public PileServiceImpl(PileRepository pileRepository) {
        this.pileRepository = pileRepository;
    }

    @Override
    public void outPile(String pileNum) {
        Pile pile = pileRepository.findByPileNum(pileNum).orElse(null);
        if(!ObjectUtils.isEmpty(pile)){
            pile.setPilesUnavailabe(pile.getPilesUnavailabe()-1);
            pile.setPilesAvailable(pile.getPilesAvailable()+1);
            pileRepository.save(pile);
        }
    }

    @Override
    public void inPile(String pileNum) {
        Pile pile = pileRepository.findByPileNum(pileNum).orElse(null);
        if(!ObjectUtils.isEmpty(pile)){
            Integer unavailabe = pile.getPilesUnavailabe()+1;
            pile.setPilesUnavailabe(unavailabe);
            pile.setPilesAvailable(pile.getPilesAvailable()-1);
            if(unavailabe == pile.getPilesCount()){
                pile.setPilesStatus(PileConstants.full);
            }
            pileRepository.save(pile);
        }
    }

    @Override
    public List<PileResponseDto> getPileList() {

        return pileRepository.findAll().stream().map(Pile::cashToPileResponseDto).collect(Collectors.toList());
    }
}
